﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Text.RegularExpressions;
using System.Data.SQLite;
using System.Data.SqlClient;
using System.Data.Sql;
using System.Data;
// Команда №1. 
// Дата последнего изменения 10.07.11

class Program
{
    private static List<string> ParseResult(string text)
    {
        List<string> list = new List<string>();
        string firstword, secondword;

        string wordInfo = text;
        int firstFormStart = wordInfo.IndexOf('"');
        int firstFormEnd = wordInfo.IndexOf('"', firstFormStart + 1);
        if ((firstFormStart | firstFormEnd) < 0)
        {
            //  int combinedStart1 = wordInfo.IndexOf("сборная");
            //  int combinedEnd1 = wordInfo.IndexOf(" ", combinedStart1 + 8);
            //  if ((combinedStart1 | combinedEnd1) < 0)
            //  {
            list.Add("0");
            list.Add("0");
            return list;
            //  };
            //  firstword = text.Substring(combinedStart1 + 1, combinedEnd1 - combinedStart1 - 1);
        }
        else
            firstword = text.Substring(firstFormStart + 1, firstFormEnd - firstFormStart - 1);
        list.Add(firstword);


        int secondFormStart = wordInfo.IndexOf('"', firstFormEnd + 1);
        int secondFormEnd = wordInfo.IndexOf('"', secondFormStart + 1);
        if ((secondFormStart | secondFormEnd) < 0)
        {
            //int combinedStart2 = wordInfo.IndexOf("сборная");
            //int combinedEnd2 = wordInfo.IndexOf(" ", combinedStart2 + 8);
            //if ((combinedStart2 | combinedEnd2) < 0)
            //{
            list.Add("0");
            list.Add("0");
            return list;
            //}
            //secondword = text.Substring(combinedStart2 + 1, combinedEnd2 - combinedStart2 - 1);
        }
        else
            secondword = wordInfo.Substring(secondFormStart + 1, secondFormEnd - secondFormStart - 1);
        list.Add(secondword);

        return list;
    }

    public static void Main()
    {

        String input;
        bool var2 = false;

        List<String> finalList1 = new List<string>();
        List<String> finalList2 = new List<string>();

        String newsItem1 = "";
        String newsItem2 = "";

        string pattern1 = @"hockey|football|basketball|volleyball";
        Match match1;
        Match match2;
        string cat = "";
        string cat1 = "";
        string cat2 = "";

        using (StreamReader sr = new StreamReader("C:\\out-lemmas-2.txt"))
        {
            while ((input = sr.ReadLine()) != null)
            {
                match1 = Regex.Match(input, pattern1);
                if (match1.Success)
                {
                    if (newsItem1 != "")
                    {
                        finalList1.Add(cat1 + '-' + cat + " : " + newsItem1);
                        newsItem1 = "";
                    }

                    cat1 = match1.Value;
                    continue;
                }

                if (input.StartsWith("/news"))
                {
                    cat = input;
                    continue;
                }

                if (input.TrimEnd('\n') == "")
                    continue;

                newsItem1 += input + "\n";
            }
            finalList1.Add(newsItem1);
        }

        cat = "";
        using (StreamReader sr2 = new StreamReader("C:\\out-lemmas-2.txt"))
        {
            while ((input = sr2.ReadLine()) != null)
            {
                match2 = Regex.Match(input, pattern1);
                if (match2.Success)
                {
                    if (newsItem2 != "")
                    {
                        finalList2.Add(cat2 + '-' + cat + " : " + newsItem2);
                        newsItem2 = "";
                    }

                    cat2 = match2.Value;
                    continue;
                }

                if (input.StartsWith("/news"))
                {
                    cat = input;
                    continue;
                }

                if (input.TrimEnd('\n') == "")
                    continue;

                newsItem2 += input + "\n";
            }
            finalList2.Add(newsItem2);
        }

        Console.WriteLine("Прочли файл. Ну и длинный же он был");
        Console.WriteLine();

        string sportPattern = @"hockey|football|basketball|volleyball";
        string scorePattern = @"вничью[ а-яА-Я]*\d+[:-]\d+|счет \d+[:-]\d+";
        string scorePattern2 = @"(\d+)[:-](\d+)";
        string newsIdPattern = @"news[0-9a-zA-Z/]*";
        string datePattern = @"[0-9]+[/][0-9]+[/][0-9]+";
        string placePattern = "стадион[ а-яА-Яa-zA-Z-\"]*";
        string placePattern2 = "\"[ а-яА-Я]+\"";
        string teamPattern = "(\"([^\",]{2,})\" ( - |одолеть|одолевать|разгромить|(об|пере|с|выи)(ы|)(грать|грывать)|победить|побеждать) \"([^\",]{2,})\")";
        string teamPatternLose = "|(\"([^\",]{2,})\" (потерпеть поражение со счёт|проиграть|проигрывать|одерживать победа над) \"([^\",]{2,})\")";
        string teamPatternEqual = "|(\"([^\",]{2,})\" (сыграть вничью с) \"([^\",]{2,})\")";
        string teamPatternSbornaja = @"|((сборная|сборный)((А-Я[А-Яа-я]{2,})\ (А-Я[А-Яа-я]{2,})))";
        string parentPattern = "";
        List<string> teams = new List<string>();

        Match scoreMatch;
        Match scoreMatch2;
        Match dateMatch;
        Match newsIdMatch;
        Match placeMatch;
        Match placeMatch2;
        Match teamMatch;
        Match parentMatch;
        Match sportMatch;

        using (StreamWriter sw = new StreamWriter("C:\\foundNews.txt"))
        {
            foreach (string newsItem in finalList1)
            {
                newsIdMatch = Regex.Match(newsItem, newsIdPattern);
                dateMatch = Regex.Match(newsItem, datePattern);
                Regex.Match(newsItem, placePattern);
                placeMatch2 = Regex.Match(Regex.Match(newsItem, placePattern).Value, placePattern2);
                teamMatch = Regex.Match(newsItem, teamPattern + teamPatternEqual + teamPatternLose + teamPatternSbornaja);
                scoreMatch2 = Regex.Match((Regex.Match(newsItem, scorePattern)).Value, scorePattern2);
                sportMatch = Regex.Match(newsItem, sportPattern);
                //parentMatch = 

                if (newsIdMatch.Success)
                {
                    sw.Write("СПОРТ " + sportMatch.Value);
                    sw.Write("      ID " + newsIdMatch.Value);
                    sw.Write("      СЧЕТ " + scoreMatch2.Value);
                    sw.Write("      ДАТА " + dateMatch.Value);
                    sw.Write("      МЕСТО " + placeMatch2.Value);
                    sw.Write("      КОМАНДЫ " + teamMatch.Value);
                    sw.WriteLine();
                }
            }
        }

        // DATA BASE
        string filename = "C:\\teams.db";
        //строка подключения
        string ConnectionString = string.Format("data source={0};New=True;UseUTF16Encoding=True", filename);

        using (SQLiteConnection connect = new SQLiteConnection(ConnectionString))
        {
            connect.Open();

            int parentId = 1;
            int eventID = 1;
            foreach (string newsItem in finalList1)
            {
                newsIdMatch = Regex.Match(newsItem, newsIdPattern);
                dateMatch = Regex.Match(newsItem, datePattern);
                placeMatch = Regex.Match(newsItem, placePattern);
                teamMatch = Regex.Match(newsItem, teamPattern);
                scoreMatch2 = Regex.Match((Regex.Match(newsItem, scorePattern)).Value, scorePattern2);
                sportMatch = Regex.Match(newsItem, sportPattern);
                placeMatch2 = Regex.Match(Regex.Match(newsItem, placePattern).Value, placePattern2);
                teams = ParseResult(teamMatch.Value);

                //parentMatch =

                if (newsIdMatch.Success)
                {
                    int sportID = 0;
                    string place = "";

                    if (sportMatch.Value == "football")
                        sportID = 1;
                    if (sportMatch.Value == "hockey")
                        sportID = 2;
                    if (sportMatch.Value == "basketball")
                        sportID = 3;
                    if (sportMatch.Value == "volleyball")
                        sportID = 4;

                    //--------------------SELECT----------------------------------
                    DataTable dt = new DataTable();
                    //создаем строку запроса

                    /* string query2 = string.Format("SELECT ID FROM teams WHERE name='"+teams[0]+"'");
                     ConnectionState previousConnectionState = ConnectionState.Closed;

                     SQLiteCommand command1 = new SQLiteCommand(query2, connect);
                     SQLiteDataAdapter adapter = new SQLiteDataAdapter(command1);
                     //заполняем таблицу
                     adapter.Fill(dt);
                 */
                    //-------------------------------------------------------------


                    //---------------------------INSERT----------------------------
                    string query1 = @"INSERT INTO events VALUES (" + eventID + "," + sportID + "," + parentId + ",'" + dateMatch.Value + "','no','" + teams[0] + "','" + teams[1] + "','" + placeMatch2.Value.Trim('"') + "','" + scoreMatch2.Value + "')";
                    parentId++;
                    eventID++;
                    SQLiteCommand command = new SQLiteCommand(query1, connect);
                    command.ExecuteNonQuery();
                    //-------------------------------------------------------------

                }
            }
            // }
            // catch (Exception e) { Console.WriteLine(e.Message); }
            connect.Close();
        }
    }
}